# Create your views here.
from myuwaterloo.harddata.models import allcourses
#from forms import RatingForm

#from models import sessionTable
from django.db.models import Q
from django import forms as forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
#from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.forms import ModelForm




def search(request):

	user = request.user
	
	query = request.GET.get('q', '')
	feelin = request.GET.get('feelin')
	results = []
	courseid = ''
	
	if request.method == 'GET':
		#if feelin == 'Feelin Fortunate':
		#	qset = (
		#		(Q(department__contains=query)|
		#		Q(instructor__icontains=query) |
		#		Q(description__icontains=query)|
		#		Q(class_field__contains=query)|
		#		Q(name_classfield__icontains=query))
		#	)
		#	results = fall08.objects.filter(qset).exclude(description='').distinct().order_by('class_field')[:1]
			
			
		#	if len(results) != 0:
		#		courseid = results[0].department + results[0].class_field
		#		coursedisplay = "http://127.0.0.1:8000/"+ str(courseid)
		#		return HttpResponseRedirect(coursedisplay)
			
		if query:
			qset = (
				(Q(department__icontains=query)|
				Q(instructor__icontains=query) |
				Q(description__contains=query)|
				Q(class_field__contains=query)|
				Q(name_classfield__icontains=query))
			)
			results = allcourses.objects.filter(qset).exclude(description='').distinct().order_by('department', 'class_field')
			
			if len(results) == 1:
				courseid = results[0].department + results[0].class_field
				coursedisplay = "http://myuwaterloocourses.com/"+ str(courseid)
				return HttpResponseRedirect(coursedisplay)
			
	return render_to_response("search/search.html",{
		"results":results,
		"query": query,
		"user":user
	})